<?php

namespace addons\qingdong\model;

use addons\qingdong\library\StaffAuth;
use app\admin\controller\qingdong\Base;
use app\admin\library\Auth;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use think\Db;
use think\Model;
use traits\model\SoftDelete;
use app\admin\model\Admin;

/**
 *员工表
 */
class Staff Extends Model {
	use SoftDelete;
    // 表名,不含前缀
    protected $name = 'qingdong_staff';
	// 开启自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	// 定义时间戳字段名
	protected $createTime = 'createtime';
	protected $updateTime = 'updatetime';
	protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'group_text',
    ];

    protected static function init()
    {
        self::beforeInsert(function ($row) {
            $changed = $row->getChangedData();
            $admin = [
                'username' => $changed['mobile'],
                'nickname' => $changed['name'],
                'password' => $changed['password'],
                'salt' => $changed['salt'],
                'avatar' => $changed['img'],
                'email' => $changed['email'],
            ];
            if(isset($changed['admin_id']) && $changed['admin_id']){
                return true;
            }
            $adminModel = new Admin();
            $result=$adminModel->validate('Admin.add')->save($admin);
            if($result == false){
                exception($adminModel->getError());
            }
            $row->admin_id = $adminModel->getLastInsID();

            $group = explode(',', $changed['group_ids']);
            foreach ($group as $value) {
                $dataset[] = ['uid' => $row->admin_id, 'group_id' => $value];
            }
            model('AuthGroupAccess')->saveAll($dataset);

            return $row;
        });

        self::beforeUpdate(function ($row) {
            $changed = $row->getChangedData();
            if(!isset($row->id)){
                return true;
            }
            $staff = self::get($row->id);
            if (empty($staff->admin_id)) {
                return $row;
            }
            //admin用户不更新
            if($staff->admin_id == 1){
                return true;
            }
            if(isset($changed['deletetime']) && $changed['deletetime']){
                Admin::where(['id' => $staff->admin_id])->delete();
                return true;
            }
            if(isset($changed['mobile']) || isset($changed['name'])
                || isset($changed['email']) || isset($changed['img']) ){
                $params = [];
                if(isset($changed['mobile'])){
                    $params['username']=$changed['mobile'];
                }
                if(isset($changed['name'])){
                    $params['nickname']=$changed['name'];
                }
                if(isset($changed['img'])){
                    $params['avatar']=$changed['img'];
                }
                if(isset($changed['email'])){
                    $params['email']=$changed['email'];
                }
                //如果有修改密码
                if (isset($changed['password'])) {
                    if ($changed['password']) {
                        $params['password'] = $changed['password'];
                        $params['salt'] = $changed['salt'];
                    }
                }

                $adminModel = new Admin();
                $result = $adminModel->save($params, ['id' => $staff->admin_id]);
                if ($result === false) {
                    exception($row->getError());
                }
            }

            if(isset($changed['group_ids'])){
                // 先移除所有权限
                model('AuthGroupAccess')->where('uid', $staff->admin_id)->delete();
                $group = explode(',', $changed['group_ids']);
                foreach ($group as $value) {
                    $dataset[] = ['uid' => $staff->admin_id, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);

            }

            return $row;
        });

    }


    // 图片
    public function getGroupTextAttr($value, $data)
    {
        if(!isset($data['group_ids'])){
            return '';
        }
        $names=AuthGroup::where(['id'=>['in',$data['group_ids']]])->column('name');
        return implode(',',$names);
    }

    public static function info()
    {
        if (StaffAuth::instance()->id) {
            return StaffAuth::instance();
        }
        $auth = new Auth();
        if ($auth->isLogin()) {
            $base = new Base();
            return $base->getStaff();
        }
        return null;
    }


	public function getImgAttr($value) {
		if ($value) {
			return cdnurl($value, true);
		} else {
			return $value;
		}
	}


	public function getCreatetimeAttr($value){
		return date('Y-m-d H:i:s',$value);
	}


	//员工业绩
	public function achievement() {
		return $this->belongsTo(Achievement::class, 'id', 'obj_id')->where(['type' => 3]);
	}

	//团队业绩
	public function teamAchievement() {
        $condition['type'] = ['in',[2,4]];
		return $this->belongsTo(Achievement::class, 'id', 'obj_id')->where($condition);
	}

	public function department() {
		return $this->belongsTo(StaffDepartment::class, 'department_id', 'id')->field('id,name as department_name')->bind('department_name');
	}

    //绑定admin账号
	public function admin() {
		return $this->belongsTo(Admin::class, 'admin_id', 'id')->field('id,username');
	}
    //角色
	public function staffrole() {
		return $this->hasOne(StaffRole::class, 'id', 'role')->field('id,name');
	}
    //上级
	public function parent() {
		return $this->belongsTo(Staff::class, 'parent_id', 'id')->field('id,name as parent_name')->bind('parent_name');
	}

	//获取员工
	public static function getList($notInIds=[]) {

		$where=['status'=>1];
		if($notInIds){
			$where['id']=['not in',$notInIds];
		}
		return self::where($where)->field('id,name')->select();
	}

    //包含当前角色
    public static function getLowerId($l_ids,$top=true){
        if(!is_array($l_ids)){
            $l_ids=explode(',',$l_ids);
        }
        $ids=AuthGroup::where(['pid' =>['in',$l_ids]])->column('id');
        if ($ids) {
            $w_ids = self::getLowerId($ids,false);
            $ids   = array_merge($ids, $w_ids);
        }else{
            $ids=[];
        }
        if($top){
            $ids=array_merge($ids,$l_ids);
        }
        return array_unique($ids);
    }

	//获取下属员工IDs
    public static function getLowerStaffId()
    {
        $staff = self::info();
        $groupIds = AuthGroupAccess::where(['uid' => $staff->admin_id])->column('group_id');
        $role_type = StaffRole::where(['id' => $staff->role])->value('role_type');
        switch ($role_type) {
            case 1://本人
                $l_ids = [];
                break;
            case 2://本人及下属
                $l_ids = self::where([
                    'parent_id' => $staff->id,
                ])->column('id');
                break;
            case 3://本部门
                $uids = AuthGroupAccess::where(['group_id' => ['in', $groupIds]])->column('uid');
                $l_ids = self::where([
                    'admin_id' => ['in', $uids],
                    'status' => 1,
                    'id' => ['neq', $staff->id]
                ])->column('id');
                break;
            case 4://仅下属部门
                $groupIds = self::getLowerId($groupIds, false);
                $uids = AuthGroupAccess::where(['group_id' => ['in', $groupIds]])->column('uid');
                $l_ids = self::where([
                    'admin_id' => ['in', $uids],
                    'status' => 1,
                    'id' => ['neq', $staff->id]
                ])->column('id');
                break;
            case 5://本部门及下属部门
                $groupIds = self::getLowerId($groupIds, true);
                $uids = AuthGroupAccess::where(['group_id' => ['in', $groupIds]])->column('uid');
                $l_ids = self::where([
                    'admin_id' => ['in', $uids],
                    'status' => 1,
                    'id' => ['neq', $staff->id]
                ])->column('id');
                break;
            case 6://全部
                $l_ids = self::where([
                    'status' => 1,
                    'id' => ['neq', $staff->id]
                ])->column('id');
                break;
        }
        if (empty($l_ids)) {//返回空 下属查询 会查询全部
            return ['-1'];
        }
        return $l_ids;
    }

	//获取全部ID
	public static function getMyStaffIds() {
		$staff = self::info();
		$ids   = [$staff->id];
		$l_ids = self::getLowerStaffId();
		$ids   = array_merge($ids, $l_ids);

		return $ids;
	}

	public static function getKeyList() {
        $staffs=self::where([])->field('id,name,img,group_ids')->select();
        $data=[];
        foreach ($staffs as $v){
            $data[$v['id']]=$v;
        }
		return $data;
	}

    public static function getGroupStaffIds($group_id)
    {
        return self::where('', 'exp', Db::raw('FIND_IN_SET(' . intval($group_id) . ',group_ids)'))->column('id');
    }
    public static function getStaff(){
        return self::where([])->column('name', 'id');
    }
    //获取自己及下属员工
    public static function allList($notInIds=[]) {
        $where['id']=['in',self::getMyStaffIds()];
        $where['status']=1;
        return self::where($where)->field('id,name')->select();
    }

    /**
     * 获取权限列表
     */
    public static function getStaffRule($type)
    {
        $row = StaffRule::where(['name' => $type])->find();
        if (!$row) {
            return [];
        }
        $rules = StaffRule::where(['pid' => $row->id])->column('name', 'id');
        $staff = self::info();
        $staffRules = StaffRole::where(['id' => $staff->role])->value('rules');
        $staffRules = explode(',', $staffRules) ?? [];
        $value = [];
        foreach ($staffRules as $r) {
            if (isset($rules[$r])) {
                $value[] = $rules[$r];
            }
        }
        return $value;
    }
}
